#!/bin/bash

config_json="/root/.config.json"
dockerfile_json="/root/.dockerfile.json"

# 帮助格式化输出
usageFormat() {
  printf "%+3s%-15s%+2s%-30s\n" "" "$1" "" "$2"
}

# 格式化输出
printFormat() {
  printf "%+10s%+2s%-10s\n" "$1" "" "$2"
}

# 输出错误
printError() {
  printf "%+8s%+1s%-10s\n" "Error:" "" "$1"
  exit 1
}

trim() {

  str="$2"
  if [ -z "$str" ]; then
    str=" "
  fi

  if [ "$str" = "/" ]; then
    str="\/"
  fi

  if [ "$1" ]; then
    echo $(echo "$1" | sed -e "s/^$str//g" | sed -e "s/$str$//g")
  else
    echo ""
  fi

  return 0
}

# 获取配置
# $2 是指定配置文件
getConfig() {
  if [ -n "$2" ]; then
    config_json="$2"
  fi
  echo "$(cat "$config_json" | jq -r ".$1")"
}

# 转化成数组
# 去除前后空格
# 替换换行符
toArray() {
  parameters=()
  i=0
  while true; do
    content=$(echo "$1" | jq ".[${i}]" | sed -e "s/ //g" | sed ':t;N;s/\n//;b t')
    if [ "$content" = "null" ]; then
      break
    fi
    parameters+=("$content")
    i=$(("$i" + 1))
  done

  echo "${parameters[@]}"

  return 0
}

# 获取json中的key列表
# 1. 获取{ local:[],remote:[] }中的key 默认获取keys
# 2. 获取{ lists:[] } 获取lists数组的值  传递格式'.lists'
# 去除"[","]"
# 去除","
jsonKeys() {

  # 配置文件地址
  config_path="$1"
  # 获取的值
  val="$2"
  if [ -z "$val" ]; then
    val="keys"
  fi

  if [[ -f "$1" ]]; then

    res=$(jq <"$config_path" -r "$val")

    res=$(echo "$res" | sed -e "s/^\[//" -e "s/\]$//" -e "s/,//g" -e "s/\"//g")

    if [ "$res" = "null" ]; then
      echo ""
    else
      echo "$res"
    fi
  fi
}

# 下载远程文件
# 单个文件
# 需要使用-u 或者 --url 参数指定完整的地址
# 需要使用-f 或者 --filepath 指定保存文件地址
# 需要使用-n 或者 --name 指定保存文件名称
downloadRemoteFile() {
  version="v1.0.1"
  remote_url=""
  filepath=""
  filename=""
  eval set -- "$(getopt -q -o hvufn: -l url:filepath:name: -- "$@")"

  while [ -n "$1" ]; do
    case "$1" in
    -h | --help)
      echo ""
      echo "Usage:"
      usageFormat "-h,--help" "查看帮助"
      usageFormat "-v,--version" "查看版本"
      usageFormat "-u,--url" "远程文件地址"
      usageFormat "-f,--filepath" "保存文件地址"
      usageFormat "-n,--name" "保存文件名称"
      exit
      ;;
    -v | --version)
      echo "version: $version"
      exit
      ;;
    -u | --url)
      remote_url=$2
      shift 2
      ;;
    -f | --filepath)
      filepath=$2
      shift 2
      ;;
    -n | --name)
      filename=$2
      shift 2
      ;;
    --)
      shift 1
      break
      ;;
    *)
      break
      ;;
    esac
  done

  if [ -z "$remote_url" ]; then
    printError "远程文件地址为空"
  fi

  if [ -z "$filepath" ]; then
    printError "保存文件地址为空"
  fi

  if [ -z "$filename" ]; then
    printError "保存文件名称为空"
  fi

  echo "Download from:$remote_url"

  if [ ! -d "$filepath" ]; then

    if ! sudo mkdir -p "$filepath" >/dev/null 2>&1; then
      printError "mkdir $filepath fial"
    fi
  fi

  sudo wget "$remote_url" -O "$filename" >/dev/null 2>&1

  save_name="$filepath/$filename"
  content=$(sudo cat "$save_name")

  if [ -z "$content" ]; then
    res="Fail(content empty)"
  else
    res="Completed"
  fi

  if [ ${#file} -ge 30 ]; then
    file="${file:0:30}..."
  fi

  i=$(("$i" + 1))

  printf "%-5s%-35s%12s \n" "to" "$filename" "$res"

  return 0
}

#
# 批量下载远程文件
# $1 本地保存的路径
# $2 文件远程地址  如：https://gitee.com/magein/shell-utils/raw/master
# $3 在远程文件中要下载的文件列表 是一个json文件，包含{dir：xxx,name:xx}
# dir是远程文件路径
# name是保存的名称
# wget最终的结果是 $2/$3中的dir
#
downloadRemoteFiles() {

  if [[ ${#1} -eq 0 || ${#2} -eq 0 || ${#3} -eq 0 ]]; then
    return 1
  fi

  save_path="$1"
  remote_raw="$2"
  remote_files=($(toArray "$3"))

  if [ ${#remote_files[@]} -gt 0 ]; then

    echo ""
    echo "Start Download from:$remote_raw"
    echo ""

    for item in "${remote_files[@]}"; do

      # 目录
      directory=$(echo "$item" | jq -r ".dir")
      # 文件前缀
      prefix=$(echo "$item" | jq -r ".prefix")
      # 要加载的文件列表
      files=$(echo "$item" | jq -r ".files")

      # 文件保存路径
      filepath=""
      if [ ${#prefix} -ne 0 ]; then
        filepath="$save_path/$prefix"
      else
        filepath="$save_path"
      fi

      if [ ! -d "$filepath" ]; then
        mkdir -p "$filepath" >/dev/null 2>&1
        if [ ! -d "$filepath" ]; then
          printError "$filepath mkdir fail"
        fi
      fi

      i=0
      while true; do

        file=$(echo "$files" | jq -r ".[$i]")

        if [ "$file" = "null" ]; then
          break
        fi

        # 保存文件名称
        filename="$filepath/$file"

        sudo wget "$remote_raw/$directory/$file" -O "$filename" >/dev/null 2>&1

        content=$(cat "$filename")

        if [ -z "$content" ]; then
          res="Fail content empty"
        else
          res="Completed"
          sudo chmod 774 "$filename" >/dev/null 2>&1
        fi

        if [ ${#file} -ge 30 ]; then
          file="${file:0:30}..."
        fi

        i=$(("$i" + 1))

        printf " %-35s%-5s%-35s%12s \n" "$file" "to" "$filename" "$res"

      done

    done
  fi

  return 0
}
